<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Animation</title>
    <style>
        .box1,
        .box2 {
            height: 100px;
            width: 100px;
            background-color: #000;
        }

        .box2 {
            margin-top: 50px;
        }

        #btnPlay, #btnPlayPromise {
            margin-top: 50px;
            font-size: 28px
        }
    </style>
</head>

<body>

    <div>
        <div class="box1"></div>
        <div class="box2"></div>
    </div>
    <div>
        <button type="button" id="btnPlay">播放 callback</button>
        <button type="button" id="btnPlayPromise">播放 Promise</button>
    </div>

    <script>
        const box1ItemEl = document.querySelector(".box1");
        const box2ItemEl = document.querySelector(".box2");

        const kyEffect = new KeyframeEffect(null, {
            transform: ['translateX(0)', 'translateX(500px)']
        },
            {
                duration: 3000,
                fill: 'forwards'
            }
        )
        btnPlay.onclick = () => {
            const ky1 = new KeyframeEffect(kyEffect);
            ky1.target = box1ItemEl;
            const ani = new Animation(ky1);
            ani.play();
            ani.onfinish = function () {
                console.log("box1 animation finished");
            }
            ani.addEventListener("finish", function () {
                console.log("box1 animation finished: addEventListener");
            })
        }

        btnPlayPromise.onclick = async () => {
            const ky1 = new KeyframeEffect(kyEffect);
            ky1.target = box2ItemEl;
            const ani = new Animation(ky1);
            ani.play();
            await ani.finished;
            console.log("box2 animation finished");
        }


    </script>
</body>

</html>